package com.chinawayltd.ews.sample.web.algorithm;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.model.TTemplate;
import com.chinawayltd.ews.sample.model.TTemplateEvent;
import com.chinawayltd.ews.sample.model.TTemplateNode;
import com.chinawayltd.ews.sample.model.algorithm.TemplateEventVO;
import com.chinawayltd.ews.sample.model.algorithm.TemplateVO;
import com.chinawayltd.ews.sample.service.algorithm.TemplateService;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.web.query.TemplateGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 任务流程
 * @author: chenxin
 * @create: 2018年4月12日 下午3:54:34
 */
@Api(tags = { "任务流程设定API" })
@RestController
@RequestMapping(value = "/web/template")
public class TemplateController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	TemplateService templateService;

    @ApiOperation(value = "流程模板列表查询接口")
    @RequestMapping(value = "/loadGirdData", method = { RequestMethod.POST })
    public ResultModel loadGirdData(TemplateGirdQuery queryParam) {
    	ResultModel model = new ResultModel();
        try {
            List<TemplateVO> list = templateService.list(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
        	logger.error("流程模板列表查询异常！"+e);
        }
        return model;
    }
	
	@ApiOperation(value = "根据ID查询流程模板接口")
	@RequestMapping(value = "/getTemplateById/{id}", method = { RequestMethod.GET })
	@ApiImplicitParam(paramType = "path", name = "id", value = "流程模板ID", dataType = "Long", required = true)
	public ResultModel getTemplateById(@PathVariable Long id) {
		ResultModel model = new ResultModel();
		try {
            TTemplate data = templateService.getTemplateById(id);
    		model.setCode(0);
    		model.setSub_code(0);
    		model.setData(new JSONObject().fluentPut("result", data));
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
            logger.error("根据ID查询流程模板出错！id：" + id, e);
        }
		return model;
	}
	
	@ApiOperation(value = "流程模板新增接口")
	@RequestMapping(value = "/add", method = { RequestMethod.POST })
	@ApiImplicitParam(paramType = "query", name = "templateName", value = "流程模板名称", dataType = "String", required = true)
	public ResultModel add(TTemplate tEmplate) {
		ResultModel model = new ResultModel();
		try {
			int result = templateService.add(tEmplate);
			if(result > 0){
				model.setData(new JSONObject().fluentPut("result", "添加成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg", "添加失败"));
	        }
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "添加失败"));
			logger.error("流程模板新增发生异常！", e);
		}
        return model;
	}
	@ApiOperation(value = "流程模板修改接口")
	@RequestMapping(value = "/update", method = { RequestMethod.POST })
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "id", value = "流程模板id", dataType = "Long", required = true),
		@ApiImplicitParam(paramType = "query", name = "templateName", value = "流程模板名称", dataType = "String", required = true),
		})
	public ResultModel update(TTemplate tEmplate) {
		ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(tEmplate.getId().toString())){
				return new ResultModel(0, 1, new JSONObject().fluentPut("sub_msg" , "修改失败"));
			}
			int result = templateService.update(tEmplate);
			if(result > 0){
				model.setData(new JSONObject().fluentPut("result", "修改成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
	        }
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
			logger.error("流程模板修改接口发生异常！", e);
		}
		return model;
	}
	
	
	@ApiOperation(value = "根据ID查询流程节点接口")
	@RequestMapping(value = "/note/getTemplateNodeById/{id}", method = { RequestMethod.GET })
	@ApiImplicitParam(paramType = "path", name = "id", value = "流程节点ID", dataType = "Long", required = true)
	public ResultModel getTemplateNodeById(@PathVariable Long id) {
		ResultModel model = new ResultModel();
		try {
            TTemplateNode data = templateService.getTemplateNodeById(id);
    		model.setCode(0);
    		model.setSub_code(0);
    		model.setData(new JSONObject().fluentPut("result", data));
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
            logger.error("根据ID查询流程节点接口出错！id：" + id, e);
        }
		return model;
	}
	
	
	@ApiOperation(value = "根据ID查看流程模板明细接口", notes = "返回的数据：\n"
			+ "template表示流程模板对象[id：流程模板id；templateName：流程模板名称]；\n"
			+ "templateNodes表示该流程模板的流程节点列表，已排序[id：流程节点id；templateId：流程模板id；nodeNo：节点编号；nodeName：节点名称；nodeType：节点类型；nodeExplain：节点描述]；\n"
			+ "templateEvents表示该模板的异常事件列表[id：异常事件id；templateId：流程模板id；eventName：事件异常名称；eventExplain：事件描述；enableState：事件启动状态]；")
	@RequestMapping(value = "/getTemplateDetailById/{id}", method = { RequestMethod.GET })
	@ApiImplicitParam(paramType = "path", name = "id", value = "流程模板ID", dataType = "Long", required = true)
	public ResultModel getTemplateDetailById(@PathVariable Long id) {
		ResultModel model = new ResultModel();
		try {
			// 判断id是否合理
            if(id == null || id <= 0){
                throw new RuntimeException("id不能为空或者少于等于0！");
            }
            // 1、通过id查询模板
            TTemplate template = templateService.getTemplateById(id);
            // 2、通过模板id查询对应的流程节点列表
            List<TTemplateNode> templateNodes = templateService.getTemplateNodeByTemplateId(id);
            // 3、通过模板id查询对应的异常事件
            List<TTemplateEvent> templateEvents = templateService.getTemplateEventByTemplateId(id);
            // 4、创建模板节点好人异常事件组装对象
            TemplateEventVO templateVO = new TemplateEventVO();
            templateVO.setTemplate(template);
            templateVO.setTemplateNodes(templateNodes);
            templateVO.setTemplateEvents(templateEvents);
            // 5、返回json对象
    		model.setCode(0);
    		model.setSub_code(0);
    		model.setData(new JSONObject().fluentPut("result", templateVO));
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
            logger.error("根据ID查看流程模板明细接口出错！id：" + id, e);
        }
		return model;
	}
	@ApiOperation(value = "根据流程模板id新增异常事件接口")
	@RequestMapping(value = "/event/addEvent", method = { RequestMethod.POST })
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "templateId", value = "流程模板id", dataType = "Long", required = true),
		@ApiImplicitParam(paramType = "query", name = "eventName", value = "异常事件名称", dataType = "String", required = true),
		@ApiImplicitParam(paramType = "query", name = "eventExplain", value = "异常事件描述", dataType = "String", required = false),
		@ApiImplicitParam(paramType = "query", name = "enableState", value = "异常事件启动状态:1是0否", dataType = "Long", required = true)
		})
	public ResultModel addEvent(TTemplateEvent tTemplateEvent) {
		ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(tTemplateEvent.getTemplateId().toString())){
				throw new BusinessException("添加失败");
			}
			int result = templateService.addEvent(tTemplateEvent);
			if(result > 0){
				model.setData(new JSONObject().fluentPut("result", "添加成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg", "添加失败"));
	        }
		} catch (BusinessException e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "添加失败"));
			logger.error("异常事件新增发生异常！", e);
		}
		return model;
	}


	@ApiOperation(value = "根据异常id和流程模板id修改异常事件接口")
	@RequestMapping(value = "/event/update", method = { RequestMethod.POST })
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "id", value = "异常事件id", dataType = "Long", required = true),
		@ApiImplicitParam(paramType = "query", name = "templateId", value = "流程模板id", dataType = "Long", required = false),
		@ApiImplicitParam(paramType = "query", name = "eventName", value = "异常事件名称", dataType = "String", required = true),
		@ApiImplicitParam(paramType = "query", name = "eventExplain", value = "异常事件描述", dataType = "String", required = false),
		@ApiImplicitParam(paramType = "query", name = "enableState", value = "异常事件启动状态1是0否", dataType = "Long", required = true)
		})
	public ResultModel updateEvent(TTemplateEvent tTemplateEvent) {
		ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(tTemplateEvent.getId().toString()) || StringUtils.isBlank(tTemplateEvent.getTemplateId().toString())){
				throw new BusinessException("修改失败");
			}
			int result = templateService.updateEvent(tTemplateEvent);
			if(result > 0){
				model.setData(new JSONObject().fluentPut("result", "修改成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
	        }
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
			logger.error("异常事件修改发生异常！", e);
		}
        return model;
	}

	@ApiOperation(value = "异常事件删除接口")
	@RequestMapping(value = "/event/delete/{id}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "id", value = "异常事件ID", dataType = "Long", required = true)
	public ResultModel deleteEvent(@PathVariable Long id) {
		ResultModel model = new ResultModel();
        try {
        	int result = templateService.deleteEvent(id);
        	if(result > 0){
				model.setData(new JSONObject().fluentPut("result", "删除成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
	        }
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "删除失败"));
			logger.error("异常事件删除发生异常！id=="+id, e);
		}
		return model;
	}
	@ApiOperation(value = "根据异常id修改异常事件状态接口")
	@RequestMapping(value = "/event/updateEventState", method = { RequestMethod.POST })
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "id", value = "异常事件id", dataType = "Long", required = true),
		@ApiImplicitParam(paramType = "query", name = "enableState", value = "异常事件启动状态1是0否", dataType = "Long", required = true)
		})
	public ResultModel updateEventState(Long id, Long enableState) {
		ResultModel model = new ResultModel();
		try {
			int result = templateService.updateEventState(id, enableState);
			if(result > 0){
				model.setData(new JSONObject().fluentPut("result", "修改成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
	        }
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "修改失败"));
			logger.error("根据异常id修改异常事件状态发生异常！", e);
		}
        return model;
	}
	
}
